import { getLyricApi, getSongDetailApi } from '@/server/modules'
import { parseLyric } from '@/utlis/format'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

// 根据歌曲id获得歌词信息
export const fetchByIdGetLyricAction = createAsyncThunk(
  'fetchByIdGetLyricAction',
  async (id: any, { dispatch }) => {
    const res: any = await getLyricApi(id)
    const lyric = parseLyric(res.lrc.lyric)
    dispatch(setLyricList(lyric))
  }
)
// 根据id获得歌曲详情
export const fetchByIdGetSongDetailAction = createAsyncThunk(
  'fetchByIdGetSongDetailAction',
  async (id: any, { dispatch, getState }: any) => {
    // 判断播放列表中是否存在该歌曲
    const playSongList = getState().audio.playSongList
    const isExist = playSongList.find((item: any) => item.id === id)
    // 没有
    if (!isExist) {
      const res: any = await getSongDetailApi(id)
      const newPlaySongList = [...playSongList]
      newPlaySongList.push(res.songs[0])
      dispatch(setPlaySongList(newPlaySongList))
      dispatch(setCurrentSong(res.songs[0]))
    } else {
      // 有
      dispatch(setCurrentSong(isExist))
    }
  }
)

type IState = {
  currentSong: any
  playSongList: any[]
  playSongIndex: number
  playMode: number // 0顺序播放 1随机播放 2单曲循环
  lyricList: any[] // 歌词列表
}

const initialState: IState = {
  currentSong: {}, // 当前播放信息
  playSongList: [], // 正在播放的歌曲信息
  playSongIndex: 0, // 正在播放的歌曲在播放列表中的索引,
  playMode: 0, // 0顺序播放 1随机播放 2单曲循环
  lyricList: [] // 歌词列表
}

const audioSlice = createSlice({
  name: 'audio',
  initialState,
  reducers: {
    setCurrentSong(state, action) {
      state.currentSong = action.payload
    },
    setPlaySongList(state, action) {
      state.playSongList = action.payload
    },
    setLyricList(state, action) {
      state.lyricList = action.payload
    },
    setAudioPrevIndex(state, action) {
      state.playSongIndex = action.payload
      state.currentSong = state.playSongList[action.payload]
    },
    setAudioNextIndex(state, action) {
      state.playSongIndex = action.payload
      state.currentSong = state.playSongList[action.payload]
    }
  }
})

export const {
  setPlaySongList,
  setCurrentSong,
  setLyricList,
  setAudioPrevIndex,
  setAudioNextIndex
} = audioSlice.actions

export default audioSlice.reducer
